package com.haike.pushjobs.jobs;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.haike.pushjobs.config.GAOLANGANFtpConfig;
import com.haike.pushjobs.mapper.SqlStringMapper;
import com.haike.pushjobs.utils.CSVUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 下载指定数据库 多个表数据. 通用多表下载任务
 */
@Slf4j
@DisallowConcurrentExecution
@Component
public class Download_www_hko_gov_hk_ToFtp_Job implements Job {

    @Autowired
    SqlStringMapper sqlStringMapper;

    @Autowired
    private GAOLANGANFtpConfig GAOLANGANFtpConfig;

    String description = "";

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        String resourcePath = "/rad_256_png/2d256nradar_202508261912.jpg";
        String filePath = Download_www_hko_gov_hk_ToFtp_Job.class.getResource(resourcePath).getPath();
        // URL解码
        String decodedPath = java.net.URLDecoder.decode(filePath, "UTF-8");
        var aaa = new FileInputStream(new File(decodedPath));
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        long funStartTime = System.currentTimeMillis();
        description = context.getJobDetail().getDescription();
        try {
            String param = context.getMergedJobDataMap().getString("param");
            log.info(description + "开始 - 参数: {}", param);

            Map<String, Object> paramMap = JSONUtil.toBean(param, Map.class);

            runTaskLeiDa(paramMap);
            runTaskWeiXinYun(paramMap);

        } catch (Exception e) {
            log.error(description + "执行出错", e);
        } finally {
            log.info(description + "执行完成: {} 毫秒", System.currentTimeMillis() - funStartTime);
            log.info("[{}]清除数据源上下文", description);
            DynamicDataSourceContextHolder.clear();
        }
    }

    //region 开始下载
    public void runTaskLeiDa(Map<String, Object> paramMap) {

        var end_date = MapUtil.getDate(paramMap, "end_date", new Date());
        var start_date = DateUtil.parse(DateUtil.format(DateUtil.offsetMinute(end_date, -120), "yyyy-MM-dd HH:00:00"));


        log.info("[{}]开始时间: {}, 结束时间: {}", description, start_date, end_date);

        // 使用从配置类读取的FTP服务器配置
        String host = GAOLANGANFtpConfig.getHost();     // FTP服务器主机地址
        int port = GAOLANGANFtpConfig.getPort();        // 端口
        String username = GAOLANGANFtpConfig.getUsername(); // 用户名
        String password = GAOLANGANFtpConfig.getPassword(); // 密码
        // 创建FTP连接配置
        cn.hutool.extra.ftp.FtpConfig config = new cn.hutool.extra.ftp.FtpConfig(host, port, username, password, Charset.defaultCharset());

        for (var date = start_date; DateUtil.compare(date, end_date) <= 0; date = DateUtil.offsetMinute(date, 6)) {
            log.info("[{}]下载数据日期: {}", description, DateUtil.format(date, "yyyy-MM-dd"));

            String temp_dir = "rad_256_png/";
            String temp_file_path = "2d256nradar_" + DateUtil.format(date, "yyyyMMddHHmm") + ".jpg";
            try {
                if (FileUtil.exist(temp_dir + temp_file_path)) {
                    log.info("[{}]文件已存在: {}", description, temp_file_path);
                    continue;
                } else {
                    log.info("[{}]开始下载: {}", description, temp_file_path);
                    // 下载url
                    String url = StrUtil.format("https://www.hko.gov.hk/wxinfo/radars/rad_256_png/{}", temp_file_path);
                    HttpUtil.downloadFile(url, temp_dir + temp_file_path);
                }
            } catch (Exception e) {
                log.error("[{}]下载图片失败: {}", description, e.getMessage());
                continue;
            }


            String dir = "/GFS+WRF+ADCIRC+SWAN/data_GaoLanGang/rad_256_png/" + DateUtil.format(date, "yyyyMMdd");

            //region 插入到Ftp
            // 建立FTP连接
            try (Ftp ftp = new Ftp(config, FtpMode.Passive)) {
                if (!ftp.exist(dir)) {
                    ftp.mkdir(dir);
                }

                if (ftp.exist(dir + "/" + temp_file_path)) {
                    log.info("[跳过]Ftp中该文件已存在: {}", temp_file_path);
                } else {
                    log.info("[{}]开始上传到ftp: {}", description, temp_file_path);

                    String filePath = getClass().getResource("/" + temp_dir + temp_file_path).getPath();
                    String decodedPath = java.net.URLDecoder.decode(filePath, "UTF-8");
                    log.info("[{}]文件路径: {}", description, decodedPath);

                    ftp.upload(dir, new File(decodedPath));
                    log.info("[{}]数据已推送到FTP.", description);
                }
            } catch (Exception e) {
                log.error("FTP操作出错: " + e.getMessage(), e);
            }
            //endregion

        }
    }


    public void runTaskWeiXinYun(Map<String, Object> paramMap) {

        var end_date = MapUtil.getDate(paramMap, "end_date", new Date());
        var start_date = DateUtil.parse(DateUtil.format(DateUtil.offsetDay(end_date, -2), "yyyy-MM-dd 00:00:00"));


        log.info("[{}]开始时间: {}, 结束时间: {}", description, start_date, end_date);

        // 使用从配置类读取的FTP服务器配置
        String host = GAOLANGANFtpConfig.getHost();     // FTP服务器主机地址
        int port = GAOLANGANFtpConfig.getPort();        // 端口
        String username = GAOLANGANFtpConfig.getUsername(); // 用户名
        String password = GAOLANGANFtpConfig.getPassword(); // 密码
        // 创建FTP连接配置
        cn.hutool.extra.ftp.FtpConfig config = new cn.hutool.extra.ftp.FtpConfig(host, port, username, password, Charset.defaultCharset());

        for (var date = start_date; DateUtil.compare(date, end_date) <= 0; date = DateUtil.offsetHour(date, 1)) {
            log.info("[{}]下载数据日期: {}", description, DateUtil.format(date, "yyyy-MM-dd"));

            //region 下载到本地
            String temp_dir = "leida24_images/";
            String temp_file_path = "h8_dcred_x8M_" + DateUtil.format(date, "yyyyMMddHH") + "0000.png";
            try {
                if (FileUtil.exist(temp_dir + temp_file_path)) {
                    log.info("[{}]文件已存在: {}", description, temp_file_path);
                    continue;
                } else {
                    log.info("[{}]开始下载: {}", description, temp_file_path);
                    // 下载url
                    String url = StrUtil.format("https://www.hko.gov.hk/wxinfo/intersat/satellite/image/images/{}", temp_file_path);
                    HttpUtil.downloadFile(url, temp_dir + temp_file_path);
                }
            } catch (Exception e) {
                log.error("[{}]下载图片失败: {}", description, e.getMessage());
                continue;
            }
            //endregion


            //region 上传到Ftp
            String dir = "/GFS+WRF+ADCIRC+SWAN/data_GaoLanGang/leida24_images/" + DateUtil.format(date, "yyyyMMdd");
            // 建立FTP连接
            try (Ftp ftp = new Ftp(config, FtpMode.Passive)) {
                if (!ftp.exist(dir)) {
                    ftp.mkdir(dir);
                }

                if (ftp.exist(dir + "/" + temp_file_path)) {
                    log.info("[跳过]Ftp中该文件已存在: {}", temp_file_path);
                } else {
                    log.info("[{}]开始上传到ftp: {}", description, temp_file_path);

                    String filePath = getClass().getResource("/" + temp_dir + temp_file_path).getPath();
                    String decodedPath = java.net.URLDecoder.decode(filePath, "UTF-8");
                    log.info("[{}]文件路径: {}", description, decodedPath);

                    ftp.upload(dir, new File(decodedPath));
                    log.info("[{}]数据已推送到FTP.", description);
                }
            } catch (Exception e) {
                log.error("FTP操作出错: " + e.getMessage(), e);
            }
            //endregion

        }
    }
    //endregion
}